import React, { Component } from 'react';
import { Input, Modal } from 'antd';
import './map.css';

const { Search } = Input;
const { confirm } = Modal;

interface AMapProps {
  value?: string;
  mapSearchCity?: string;
  mapStyle?: any;
  onChange?: (lnglat: string) => void;
  onCityChange?: (cityCode: string) => void;
}

interface AMapState {
  searchCity: string;
  showError: boolean;
}

let map: any;
let infoWin: any;
let administrative: any;
let localsearch: any;
let bounds: any;
let geocode: any;

class TianMapComponent extends Component<AMapProps, AMapState> {
  constructor(props: AMapProps) {
    super(props);
    this.state = {
      searchCity: props.mapSearchCity || '',
      showError: false,
    };
  }

  showPosition(marker, name, winHtml) {
    if (infoWin) {
      map.removeOverLay(infoWin);
      infoWin = null;
    }
    let html = '<h3>' + name + '</h3>';
    html += winHtml;
    infoWin = new T.InfoWindow(html, new T.Point([0, 0]));
    marker.openInfoWindow(infoWin);
  }

  onLoad() {
    const { value, mapSearchCity, onChange, onCityChange } = this.props;
    const parentNode = document.body || document.head;
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = `https://api.tianditu.gov.cn/api?v=4.0&tk=9bde65a82ff7d48d6c107a3e9af63e2e`;
    script.crossOrigin = 'anonymous';

    script.onerror = (e) => {
      confirm({
        title: '地图加载不稳定，请刷新网页重试',
        okText: '现在刷新',
        cancelText: '知道了',
        onOk() {
          location.reload();
        },
        onCancel() {},
      });
      this.setState({
        showError: true
      })
    };
    script.onload = () => {
      bounds = new T.LngLatBounds(
        new T.LngLat(116.25183, 27.48391),
        new T.LngLat(119.63013, 29.41568),
      );
      map = new T.Map('mapcontainer', {
        minZoom: 8,
        maxZoom: 18,
        projection: 'EPSG:4326',
        maxBounds: bounds,
        center: new T.LngLat(117.942962, 28.455832),
        zoom: 10,
      });
      //地址编码
      geocode = new T.Geocoder();
      //注册点击
      map.addEventListener('click', (ev) => {
        map.clearOverLays();
        // 触发事件的地理坐标，T.LngLat 类型
        const lnglat = ev.lnglat;
        const mIcon = new T.Icon({
          iconUrl: 'https://ossworkerweb.jxsrnmg.com/worker_supervision_oa/img/marker-blue.png',
          iconSize: new T.Point(20, 35),
        });
        //创建标注对象
        const m1 = new T.Marker(lnglat, {
          icon: mIcon,
        });
        m1.addEventListener('click', () => {});
        //向地图上添加标注
        map.addOverLay(m1);
        const zm = map.getZoom();
        if (zm > 16) {
          map.panTo(lnglat);
        } else {
          map.panTo(lnglat, 16);
        }
        if (onChange) {
          onChange(JSON.stringify([lnglat.lng, lnglat.lat]));
        }
        geocode.getLocation(lnglat, (result) => {
          if (result.getStatus() == 0) {
            if (onCityChange) {
              onCityChange(result.addressComponent.county_code);
            }
          }
        });
      });
      //初始化
      if (value) {
        const lng_lat = JSON.parse(value);
        const lnglat1 = new T.LngLat(lng_lat[0], lng_lat[1]);
        const mIcon = new T.Icon({
          iconUrl: 'https://ossworkerweb.jxsrnmg.com/worker_supervision_oa/img/marker-blue.png',
          iconSize: new T.Point(20, 35),
        });
        const m_d = new T.Marker(lnglat1, {
          icon: mIcon,
        });
        map.addOverLay(m_d);
        const mzm = map.getZoom();
        if (mzm > 16) {
          map.panTo(lnglat1);
        } else {
          map.panTo(lnglat1, 16);
        }
      }
      try {
        //创建搜索对象
        const config = {
          pageCapacity: 10, //每页显示的数量
          onSearchComplete: this.searchResult, //接收数据的回调函数
        };
        localsearch = new T.LocalSearch(map, config);
        administrative = new T.AdministrativeDivision();
      } catch (error) {
        console.log('map load error');
      }
    };
    parentNode.appendChild(script);
  }

  searchResult(result: any) {
    map.clearOverLays();
    //根据返回类型解析搜索结果
    switch (parseInt(result.getResultType())) {
      case 1:
        //解析点数据结果
        // this.pois(result.getPois());
        const obj = result.getPois();
        if (obj) {
          let fastLnglat: any;
          //坐标数组，设置最佳比例尺时会用到
          for (let i = 0; i < obj.length; i++) {
            const lnglatArr = obj[i].lonlat.split(' ');
            const lnglat = new T.LngLat(lnglatArr[0], lnglatArr[1]);
            //创建标注对象
            const mIcon = new T.Icon({
              iconUrl: 'https://ossworkerweb.jxsrnmg.com/worker_supervision_oa/img/marker_red.png',
              iconSize: new T.Point(20, 27),
            });
            const marker = new T.Marker(lnglat, {
              icon: mIcon,
            });
            //地图上添加标注点
            map.addOverLay(marker);
            if (i == 0) {
              fastLnglat = lnglat;
            }
          }
          map.panTo(fastLnglat);
        }
        break;
      case 2:
        //解析统计城市
        // this.statistics(result.getStatistics());
        break;
    }
  }

  onSearch(value: string) {
    if (localsearch && localsearch.searchInBounds) {
      localsearch.searchInBounds(value, bounds);
    }
    // localsearch.search(value, 2);
  }

  componentDidMount() {
    this.onLoad();
  }

  static getDerivedStateFromProps(props, current_state) {
    if (props.mapSearchCity !== current_state.searchCity) {
      if (map && administrative) {
        const ols = map.getOverlays();
        if (ols.length <= 0) {
          const config = {
            needSubInfo: false,
            needAll: false,
            needPolygon: false,
            needPre: false,
            searchType: 0,
            searchWord: '156' + props.mapSearchCity,
          };
          if (administrative.search) {
            administrative.search(config, (result) => {
              if (result.getStatus() == 100) {
                const data = result.getData();
                map.panTo(new T.LngLat(data.lnt, data.lat));
              }
            });
          }
        }
      }

      return {
        searchCity: props.mapSearchCity,
      };
    }
    return null;
  }

  componentWillUnmount() {}

  render() {
    const { mapStyle } = this.props;
    const { showError } = this.state;
    return (
      <div className="home_div">
        <div id="mapcontainer" className="map" style={mapStyle} />
        <div id="myPageTop" className="myPageTop">
          <Search
            id="map_input"
            placeholder="名称搜索"
            size={'small'}
            onSearch={this.onSearch}
            enterButton={'搜索'}
          />
        </div>
        {showError && (
          <div className='mapError'>地图加载不稳定，请尝试刷新网页重试</div>
        )}
      </div>
    );
  }
}

export default TianMapComponent;
